<template>
  <view>
    <view class="goods-list">
      <view v-for="(goods, i) in goodsList" :key="i" @click="gotoDetail(goods)">
      <my-goodss :goods-item="goods"></my-goodss>
      </view>
    </view>
  </view>
</template>

<script setup>
  import {ref, reactive} from "vue"
  import {onLoad, onReachBottom, onPullDownRefresh} from "@dcloudio/uni-app"
  
  const queryObj = reactive({query: "", cid: "", pageNum: 1, pageSize: 10})
  let goodsList = ref([])
  //总数量，用来实现分页
  let total = ref(0)
  let isLoading = ref(false)
  
  //onLoad，监听页面加载，其参数为上个页面传递的数据
  onLoad((options) => {
    queryObj.query = options.query || ""
    queryObj.cid = options.cid || ""
    getGoodsList()
  })
  
 async function getGoodsList(cb) {
    isLoading.value = true
    const {data} = await uni.$http.get("/api/public/v1/goods/search", queryObj)
    
    cb && cb()
    isLoading.value = false
    if(data.meta.status !== 200) return uni.$showMsg();
    goodsList.value = [...goodsList.value, ...data.message.goods]
    total.value = data.message.total
  }
  function gotoDetail(item) {
    uni.navigateTo({
      url: "/subpkg/goods_detail/goods_detail?goods_id=" + item.goods_id
    })
  }
  onReachBottom(() =>{
    if(queryObj.pageNum * queryObj.pageSize >= total.value) return uni.$showMsg("数据加载完毕")
    //如果有数据正在加载就不再请求数据
    if(isLoading.value) return
    
    queryObj.pageNum += 1
    getGoodsList()
    console.log("OK")
  })
  onPullDownRefresh(() => {
    queryObj.pageNum = 1
    total.value = 0
    goodsList.value = []
    getGoodsList(() => {uni.stopPullDownRefresh()})
  })
</script>

<style lang="scss">

</style>
